<template>
  <view class="login-container">
    <view class="login-box scale-in">
      <view class="logo-area">
        <image
          class="logo"
          src="@/static/image/logo.png"
          mode="aspectFit"
        ></image>
        <text class="system-name">ERP管理系统</text>
      </view>
      <up-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        class="login-form"
      >
        <up-form-item prop="username">
          <up-input
            v-model="formData.username"
            placeholder="请输入用户名"
            prefixIcon="account"
            class="login-input"
          ></up-input>
        </up-form-item>
        <up-form-item prop="password">
          <up-input
            v-model="formData.password"
            type="password"
            placeholder="请输入密码"
            prefixIcon="lock"
            class="login-input"
          ></up-input>
        </up-form-item>
        <view class="options-row">
          <label class="remember-box">
            <up-checkbox-group
              v-model="rememberMe"
              placement="row"
              @change="handleRememberMeChange"
            >
              <up-checkbox
                :customStyle="{ color: '#fff' }"
                label="记住我"
                name="true"
                >记住我</up-checkbox
              >
            </up-checkbox-group>
          </label>
          <text class="forget-link">忘记密码?</text>
        </view>
        <view class="btn-container">
          <up-button
            type="primary"
            @click="submit"
            class="login-btn"
            :loading="isLoading"
            >登录</up-button
          >
        </view>
      </up-form>
      <view class="login-footer">
        <text>© {{ currentYear }} ERP管理系统 版权所有</text>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, computed } from "vue";
import { login } from "@/api/auth";
import {
  setTokenWithTimestamp,
  isValidToken,
  removeToken,
  removeRefreshToken,
  setRefreshToken,
} from "@/utils/auth";
import { useUserStore } from "@/stores/user";
import { onReady } from "@dcloudio/uni-app";
import request from "@/utils/request";
import { getRefreshToken, getToken } from "@/utils/auth";

const userStore = useUserStore();

const formData = ref({
  username: "",
  password: "",
});

const formRef = ref(null);
const rememberMe = ref(false);
const isLoading = ref(false);

// 获取当前年份
const currentYear = computed(() => new Date().getFullYear());

const rules = ref({
  username: {
    type: "string",
    required: true,
    message: "用户名不能为空",
    trigger: ["blur"],
  },
  password: {
    type: "string",
    required: true,
    message: "密码不能为空",
    trigger: ["blur"],
  },
});

const handleRememberMeChange = (value) => {
  console.log("rememberMe changed:", value);
  if (value && value.length > 0) {
    rememberMe.value = true;
  } else {
    rememberMe.value = false;
  }
  console.log("rememberMe:", rememberMe.value);
};

const submit = async () => {
  // 先验证表单
  if (!formRef.value) return;

  try {
    await formRef.value.validate();
    isLoading.value = true;

    const res = await login({
      ...formData.value,
      rememberMe: rememberMe.value,
    });
    if (res.success) {
      console.log(res);
      // 设置Token并记录时间戳
      setTokenWithTimestamp(res.data.token);
      setRefreshToken(res.data.refreshToken);
      console.log(res.data);
      userStore.setUserInfo({
        username: res.data.username,
        nickname: res.data.nickname,
        permissions: res.data.permissions,
      });

      // 如果选择了记住我，可以在这里处理相关逻辑

      // 显示登录成功提示
      uni.showToast({
        title: "登录成功",
        icon: "success",
        duration: 1500,
      });

      // 跳转到首页
      setTimeout(() => {
        uni.switchTab({
          url: "/pages/index/index",
        });
      }, 1000);
    }
  } catch (error) {
    console.log("表单验证失败");
    uni.showToast({
      title: "登录失败",
      icon: "error",
      duration: 2000,
    });
  } finally {
    isLoading.value = false;
  }
};

onReady(async () => {
  uni.setNavigationBarTitle({
    title: "登录",
  });

  // 设置表单验证规则前检查 formRef 是否存在
  if (formRef.value) {
    formRef.value.setRules(rules.value);
  } else {
    console.error("formRef is null, cannot set rules");
  }
  // 如果已经登录后,直接跳转到首页
  const token = getToken();
  if (token && isValidToken(token)) {
    uni.switchTab({
      url: "/pages/index/index",
    });
    return;
  } else {
    const refreshToken = getRefreshToken();
    if (refreshToken) {
      const token = await request.refreshToken(refreshToken);
      if (token) {
        return uni.switchTab({
          url: "/pages/index/index",
        });
      }
    }
    removeToken();
    removeRefreshToken();
  }
});
</script>

<style scoped lang="scss">
.login-container {
  width: 100%;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background-image: linear-gradient(
      to bottom right,
      rgba(24, 144, 255, 0.7),
      rgba(9, 109, 217, 0.8)
    ),
    url("http://picsum.photos/600/800?blur=2");
  background-size: cover;
  background-position: center;
  position: relative;

  &::before {
    content: "";
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: radial-gradient(
      ellipse at center,
      rgba(0, 0, 0, 0),
      rgba(0, 0, 0, 0.3)
    );
  }

  .login-box {
    width: 84%;
    max-width: 600rpx;
    background-color: rgba(255, 255, 255, 0.95);
    border-radius: 20rpx;
    padding: 50rpx 40rpx;
    box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.25);
    position: relative;
    z-index: 1;
    backdrop-filter: blur(10px);
    border: 1rpx solid rgba(255, 255, 255, 0.2);

    .logo-area {
      display: flex;
      flex-direction: column;
      align-items: center;
      margin-bottom: 50rpx;

      .logo {
        width: 140rpx;
        height: 140rpx;
        margin-bottom: 24rpx;
        border-radius: 20rpx;
        box-shadow: 0 6rpx 16rpx rgba(0, 0, 0, 0.1);
      }

      .system-name {
        font-size: 42rpx;
        font-weight: bold;
        color: var(--text-primary);
        letter-spacing: 2rpx;
        background: linear-gradient(
          120deg,
          var(--primary-color),
          var(--primary-dark)
        );
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
      }
    }

    .login-form {
      margin-bottom: 30rpx;

      .login-input {
        height: 90rpx;
        border-radius: 45rpx;
        overflow: hidden;

        :deep(.up-input__content__field) {
          font-size: 28rpx;
        }

        :deep(.up-icon) {
          color: var(--primary-color);
        }
      }
    }

    .options-row {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin: 16rpx 10rpx 40rpx;

      .remember-box {
        font-size: 24rpx;
        color: var(--text-secondary);
      }

      .forget-link {
        font-size: 24rpx;
        color: var(--primary-color);
      }
    }

    .btn-container {
      margin-top: 40rpx;

      .login-btn {
        width: 100%;
        height: 90rpx;
        font-size: 32rpx;
        letter-spacing: 4rpx;
        border-radius: 45rpx;
        background: linear-gradient(
          to right,
          var(--primary-color),
          var(--primary-dark)
        );
        box-shadow: 0 8rpx 16rpx rgba(24, 144, 255, 0.3);
        transition: all 0.3s ease;

        &:active {
          transform: translateY(3rpx);
          box-shadow: 0 4rpx 8rpx rgba(24, 144, 255, 0.2);
        }
      }
    }

    .login-footer {
      text-align: center;
      margin-top: 60rpx;
      font-size: 24rpx;
      color: var(--text-tertiary);
    }
  }
}

/* 适配较大屏幕 */
@media screen and (min-width: 768px) {
  .login-box {
    max-width: 750rpx;
    padding: 60rpx 50rpx;

    .logo-area {
      .logo {
        width: 160rpx;
        height: 160rpx;
      }

      .system-name {
        font-size: 48rpx;
      }
    }

    .login-btn {
      height: 100rpx;
      font-size: 36rpx;
    }
  }
}
</style>
